package com.dqp.cslggroup.School;


import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewStub;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import androidx.appcompat.widget.Toolbar;
import com.alibaba.fastjson.JSONObject;
import com.dqp.cslggroup.Api.schoolApi;
import com.dqp.cslggroup.EventBus.MessageEvent;
import com.dqp.cslggroup.R;
import com.dqp.cslggroup.UI.BaseActivity;
import com.dqp.cslggroup.Util.NetCheckUtil;
import com.dqp.cslggroup.Util.Result;
import com.dqp.cslggroup.Util.StringUtil;
import com.dqp.cslggroup.Util.ToastUtil;
import com.dqp.cslggroup.bean.ip;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Objects;

import static com.dqp.cslggroup.UI.MyApplication.getContext;

public class DormitoryIP extends BaseActivity {
    private String ssl, bedid, roomid, text;
    private String xq = "2";
    private Button CxBt;
    private Button web_ip;
    private Spinner bed_num;
    private EditText ldh, room_id;
    private RadioButton DH, DN;
    private TextView textView;
    private ViewStub viewstub_loading;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.room_ip);
        EventBus.getDefault().register(this);
        Toolbar toolbar = findViewById(R.id.include_toolbar);
        toolbar.setTitle("");
        setSupportActionBar(toolbar);
        initIPComp();
        Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
        if (NetCheckUtil.checkNet(DormitoryIP.this)) {
            initFunc();
        } else {
            ToastUtil.showToast("请连接网络！");
        }
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0 && resultCode == RESULT_OK) {
            setResult(RESULT_OK);
            super.onDestroy();
            this.finish();
        }
    }

    private void initIPComp() {
        RadioGroup radioGroups = findViewById(R.id.XQ_XZ);
        DH = findViewById(R.id.DH_XQ);
        DN = findViewById(R.id.DN_XQ);
        bed_num = findViewById(R.id.bed_spinner);
        CxBt = findViewById(R.id.cx_IP);
        room_id = findViewById(R.id.ip_room);
        web_ip = findViewById(R.id.IP_web);
        ldh = findViewById(R.id.ip_ssl);
        textView = findViewById(R.id.ip_text);
        viewstub_loading = findViewById(R.id.viewstub_loading);
        radioGroups.setOnCheckedChangeListener((group, checkedId) -> {
            if (DN.isChecked()) {
                xq = "2";
            }
            if (DH.isChecked()) {
                xq = "1";
            }
        });
    }

    @SuppressLint("HandlerLeak")
    private void initFunc() {
        InputMethodManager manager = ((InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE));
        CxBt.setOnClickListener(view -> {
            ssl = ldh.getText().toString();
            bedid = bed_num.getSelectedItem().toString();
            System.out.println(bedid);
            roomid = room_id.getText().toString();
            if (manager != null)
                manager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            if (StringUtil.isEmpty(ssl) || StringUtil.isEmpty(roomid, 2)) ToastUtil.showToast("请输入正确的宿舍号!");
            else {
                viewstub_loading.setVisibility(View.VISIBLE);
                new Thread(() -> {
                    JSONObject jsonObject = schoolApi.getIp(xq, ssl, roomid, bedid);
                    if (jsonObject != null && Result.jsonResultIsTure(jsonObject)) {
                        JSONObject result = jsonObject.getJSONObject("ip");
                        ip ip = result.toJavaObject(ip.class);
                        EventBus.getDefault().post(new MessageEvent("DormitoryIP", 1, ip));
                    } else {
                        EventBus.getDefault().post(new MessageEvent("DormitoryIP", 12, null));
                    }
                }).start();
            }
        });

        web_ip.setOnClickListener(view -> {
            Uri uri = Uri.parse("https://ipcx2.cslg.edu.cn/");
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent);
        });

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        if (event.getEvent().equals("DormitoryIP")) {
            switch (event.getWhat()) {
                case 1:
                    ip ip = (com.dqp.cslggroup.bean.ip) event.getObj();
                    text = "宿舍：" + ip.getSsl() + "-" + ip.getRoomid() + "\n"
                            + "校区：" + ip.getCampus() + "\n"
                            + "床位号：" + ip.getBedid() + "\n"
                            + ip.getIp() + "\n"
                            + ip.getSubnetMask() + "\n"
                            + ip.getGateway() + "\n"
                            + getResources().getString(R.string.ip);
                    textView.setText(text);
                    viewstub_loading.setVisibility(View.GONE);
                    ToastUtil.showToast("长按即可复制查询结果！");
                    break;
                case 2:
                    viewstub_loading.setVisibility(View.GONE);
                    ToastUtil.showToast("查询数据不存在！");
                    break;
                case 3:
                    viewstub_loading.setVisibility(View.GONE);
                    ToastUtil.showToast("网络请求超时！");
                    break;
            }
        }
    }
}